<?php

namespace app\admin\controller\miniapp;

use app\common\controller\Backend;
use EasyWeChat\OpenPlatform\Authorizer\MiniProgram\Application as MiniProgram;
use think\Cache;
use uctoo\ThinkEasyWeChat\Facade;
use think\Queue;
use app\wechatopen\job\UploadCloudDb;
use app\wechatopen\job\UploadCloudFunction;


/**
 * 小程序版本管理
 *
 * @icon fa fa-circle-o
 */
class Version extends Backend
{
    /**
     * Version模型对象
     * @var \app\admin\model\miniapp\Version
     */
    protected $model = null;
    protected $openPlatform;    //第三方平台
    /**
     * @var MiniProgram $miniapp
     */
    protected $miniapp;         //已在第三方平台授权的小程序

    /**
     * 引入微信控制器的traits
     */
    use \app\wechatopen\library\traits\Wechatopen;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\miniapp\Version;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("auditStatusList", $this->model->getAuditStatusList());
        $wechatopenInfoConfig = Cache::get('wechatopen_config');
        $this->openPlatform = Facade::openPlatform($wechatopenInfoConfig['app_id'],$wechatopenInfoConfig);
        $applet = session('applet_info');
        $miniappinfo = $applet['miniprograminfo'];
        if(!isset($miniappinfo)){
            $this->error(__('Select miniapp to operate'));
        }
        $this->miniapp = $this->openPlatform->miniProgram($applet['appid'], $applet['authorizer_refresh_token']);
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','template_id','user_version','status','audit_status','auditid']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 上传小程序模板到小程序帐号
     *
     */
    public function commit($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $applet = session('applet_info');
        $miniappinfo = $applet['miniprograminfo'];
        if(!isset($miniappinfo)){
            $this->error(__('Select miniapp to commit'));
        }
        if ($this->request->isAjax()) {
            $res = $this->miniapp->code->commit($row->template_id,$row->ext_json,$row->user_version,$row->user_desc);
            $ext_config = $row->ext_json;
            $this->wxResult($res, false, function () use ($applet, $ext_config) {
                // 添加数据集合
                if(isset($ext_config['cloud_dbs'])){
                    $dbQueueData = [
                        'applet' => $applet,
                        'cloud_dbs' => $ext_config['cloud_dbs']
                    ];
                    Queue::push(UploadCloudDb::class, $dbQueueData, 'uploadCloudDbQueue');
                }
                if(isset($ext_config['cloud_functions'])){
                    // 上传云函数
                    $funcQueueData = [
                        'applet' => $applet,
                        'cloud_functions' => $ext_config['cloud_functions']
                    ];
                    Queue::push(UploadCloudFunction::class, $funcQueueData, 'uploadCloudFunctionQueue');
                }
            });

            $this->success("上传小程序模板成功", null, ['id' => $ids]);
        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

    /**
     * 获取体验小程序的体验二维码页面
     * @param  int $id 产品id
     */
    public function qrcode($ids)
    {
        $this->assign('ids', $ids);
        return $this->fetch();
    }

    /**
     * 获取体验小程序的体验二维码（仅供第三方开发者代小程序调用）
     *
     */
    public function getqrcode($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $res = $this->miniapp->code->getQrCode();
        $this->view->assign("row", $row->toArray());
        return $res;
    }

    /**
     * 提交审核
     *
     */
    public function submitaudit($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            $res = $this->miniapp->code->submitAudit([], null, null);
            $ext_config = $row->ext_json;
            $this->wxResult($res, 'submit_audit', function ($data) use ($ext_config,$ids) {
                $this->model->save(['audit_status' => 2,'auditid' => $data['auditid']],['id' => $ids]);  //更新提交审核状态
            });
            $this->success("提交审核成功", null, ['id' => $ids]);
        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

    /**
     * 提交发布
     *
     */
    public function release($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            $res = $this->miniapp->code->release();
            $ext_config = $row->ext_json;
            $this->wxResult($res, 'submit_audit', function ($data) use ($ext_config,$ids) {
                $this->model->save(['status' => 2],['id' => $ids]);  //更新已发布状态
            });
            $this->success("提交发布成功", null, ['id' => $ids]);
        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

}
